﻿using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DynamicGeometry
{
    public abstract class PolygonBase : ShapeBase<System.Windows.Shapes.Polygon>
    {
        protected override int DefaultZOrder()
        {
            return (int)ZOrder.Polygons;
        }

        public override IFigure HitTest(System.Windows.Point point)
        {
            // HitTest receives logical coordinates, so because we need to talk to the outside world (WPF)
            // we need to convert to WPF's physical coordinates (pixels) from our internal logical coordinates
            point = ToPhysical(point);

#if SILVERLIGHT
            // surprisingly, UIElement.HitTest expects the point to be in global coordinates
            // and not in the coordinates of its parent.
            // That's why we need to translate the argument point
            // from Canvas coordinates to global coordinates
            
            // get the transform that will convert Canvas coordinates to RootVisual coordinates
            var transform = Shape.TransformToVisual(Application.Current.RootVisual);
            // and apply it to the argument point
            var hitTestPoint = transform.Transform(point);

            // finally, call HitTest with the point in global coordinates
            return VisualTreeHelper.FindElementsInHostCoordinates(hitTestPoint, Shape).Any() ? this : null;
#else
            var result = VisualTreeHelper.HitTest(Shape, point);
            return result != null ? this : null;
#endif
        }

        [PropertyGridVisible]
        public double Area
        {
            get
            {
                return Dependencies.ToPoints().Area();
            }
        }

        protected override System.Windows.Shapes.Polygon CreateShape()
        {
            return Factory.CreatePolygonShape();
        }
    }
}
